package com.avic.modules.log.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 属性差异 工具类
 */
public class ContrastObjUtil {

    public static String comparObj(Object oldBean, Object newBean) {
        JSONArray array = new JSONArray();
        try {
            Class clazz = oldBean.getClass();
            Field[] fields = oldBean.getClass().getDeclaredFields();
            int i = 1;

            for (Field field : fields) {
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(oldBean);
                Object o2 = getMethod.invoke(newBean);
                if (o1 == null || o2 == null) {
                    continue;
                }
                if (!o1.toString().equals(o2.toString())) {
                    // 要显示的字段名
//                    String fieldName = "";
//                    fieldName = field.getName();

                    JSONObject json = new JSONObject();
//                    json.put("type", fieldName);
                    json.put("修改后", o1);
                    json.put("修改前", o2);
                    array.add(json);
                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return array.toJSONString();
    }
}
